package me.leiusual.sharing.ui.useraccount

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_user_account.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.useraccount.adapter.UserAccountAdapter
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-08-06
 * description:
 */
class UserAccountFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: UserAccountViewModel by viewModels { factory }

  private val args: UserAccountFragmentArgs by navArgs()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_user_account, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    recycler_view.adapter = UserAccountAdapter(args.type) {
      Timber.v("点击：%s", it)

      val navDirections = UserAccountFragmentDirections.actionUserAccountFragmentToUserAccountDetailFragment(args.type, it.id)
      findNavController().navigate(navDirections)
    }

    when (args.type) {
      "user" -> {
        text_view_title.text = "我的积分"
      }
      "store" -> {
        text_view_title.text = "店铺货款"
      }
    }

    observeData()
    viewModel.userAccountList(args.type)
  }

  private fun observeData() {
    viewModel.userAccountList.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("userAccountList = %s", it)
      when (it) {
        is Data.Loading -> {
          state_constraint_layout.showProgress()
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()

          val adapter = recycler_view.adapter as UserAccountAdapter
          adapter.submitList(it.data)
        }
      }
    })
  }
}